package db

import (
	"database/sql"
	"fmt"
	_ "github.com/mattn/go-sqlite3"
	"os"
	"code.google.com/p/my-little-rpg/goMyLittleRPG/user"
	"errors"
)

func Exists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil { return true, nil }
	if os.IsNotExist(err) { return false, nil }
	return false, err
}

func CreateDB(dbname string) {
	db, err := sql.Open("sqlite3", "./" + dbname)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer db.Close()
	sqls := []string{
		"create table user ("+
		"id integer not null primary key autoincrement,"+
		"username text not null,"+
		"password text,"+
		"age integer"+
		")",
		"delete from user",
	}
	for _, sql := range sqls {
		_, err = db.Exec(sql)
		if err != nil {
			fmt.Printf("%q: %s\n", err, sql)
			return
		}
	}

}

func DeleteDB(name string) {
	os.Remove("./" + name)
}

func CheckUsername(username string, dbname string) (bool, error) {
	db, err := sql.Open("sqlite3", "./" + dbname)
	if err != nil {
		fmt.Println(err)
		return false, err
	}
	defer db.Close()
	stmt, err := db.Prepare("select username from user where username = ?")
	if err != nil {
		fmt.Println(err)
		return  false, err
	}
	defer stmt.Close()
	var n string
	err = stmt.QueryRow(username).Scan(&n)
	if err != nil {
		fmt.Println("Warning:", err)
		//return err
	}
	if n == username{
		return true, nil
	}
	return false, nil
}

func InsertUser(u *user.User, dbname string) error {
	db, err := sql.Open("sqlite3", "./" + dbname)
	if err != nil {
		fmt.Println(err)
		return err
	}
	defer db.Close()
	//--------------------------
	stmt, err := db.Prepare("select username from user where username = ?")
	if err != nil {
		fmt.Println(err)
		return err
	}
	defer stmt.Close()
	var username string
	err = stmt.QueryRow(u.Username()).Scan(&username)
	if err != nil {
		fmt.Println(err)
		//return err
	}
	if username == u.Username(){
		return errors.New("Username already exists")
	}
	//---------------------------
	fmt.Println("...trying...")
	tx, err := db.Begin()
	if err != nil {
		fmt.Println(err)
		return err
	}
	stmt, err = tx.Prepare("insert into user(username) values(?)")
	if err != nil {
		fmt.Println(err)
		return err
	}
	defer stmt.Close()
	_, err = stmt.Exec(u.Username())
	if err != nil {
		fmt.Println(err)
		return err
	}
	tx.Commit()

	return nil

}

func SelectAllUsers(dbname string) {
	db, err := sql.Open("sqlite3", "./" + dbname)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer db.Close()
	rows, err := db.Query("select id, username from user")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer rows.Close()
	for rows.Next() {
		var id int
		var username string
		rows.Scan(&id, &username)
		println(id, username)
	}
	rows.Close()

}
func SelectUser(id int, dbname string) {
	db, err := sql.Open("sqlite3", "./" + dbname)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer db.Close()
	stmt, err := db.Prepare("select username from user where id = ?")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer stmt.Close()
	var username string
	err = stmt.QueryRow(id).Scan(&username)
	if err != nil {
		fmt.Println(err)
		return
	}
	println(username)
}

/*
func main() {
	os.Remove("./foo.db")

	db, err := sql.Open("sqlite3", "./foo.db")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer db.Close()

	sqls := []string{
		"create table user (id integer not null primary key, name text)",
		"delete from foo",
	}
	for _, sql := range sqls {
		_, err = db.Exec(sql)
		if err != nil {
			fmt.Printf("%q: %s\n", err, sql)
			return
		}
	}

	tx, err := db.Begin()
	if err != nil {
		fmt.Println(err)
		return
	}
	stmt, err := tx.Prepare("insert into user(id, name) values(?, ?)")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer stmt.Close()
	for i := 0; i < 100; i++ {
		_, err = stmt.Exec(i, fmt.Sprintf("こんにちわ世界%03d", i))
		if err != nil {
			fmt.Println(err)
			return
		}
	}
	tx.Commit()

	rows, err := db.Query("select id, name from foo")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer rows.Close()
	for rows.Next() {
		var id int
		var name string
		rows.Scan(&id, &name)
		println(id, name)
	}
	rows.Close()

	stmt, err = db.Prepare("select name from foo where id = ?")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer stmt.Close()
	var name string
	err = stmt.QueryRow("3").Scan(&name)
	if err != nil {
		fmt.Println(err)
		return
	}
	println(name)
	*/
